<template>
  <p-card :bordered="false" :class="'cust-erp-sub-tab'">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="单据号">
              <p-input-search
                placeholder="请输入单据号"
                v-model="queryParam.billNum"
                @search="onSearch"
              ></p-input-search>
            </p-form-item>
          </p-col>
        </p-row>
      </p-form>
    </div>
    <!-- 查询区域-END -->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <p-radio-group :value="size" @change="handleSizeChange">
        <p-radio-button :value="item.value" :key="item.value" v-for="item in state">{{item.text}}</p-radio-button>
      </p-radio-group>

      <p-button @click="handleAdd" type="primary" style="margin-left: 70px"
        >新增</p-button
      >
      <p-button @click="handleChange" type="primary">编辑</p-button>

      <!-- 高级查询区域 -->
      <j-super-query
        :fieldList="fieldList"
        ref="superQueryModal"
        @handleSuperQuery="handleSuperQuery"
      ></j-super-query>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;text-align:right">
        <span s>
          <p-divider type="vertical" />
          <p-popover
            title="自定义列"
            trigger="click"
            placement="leftBottom"
            :overlay-style="getWidth"
          >
            <template slot="content">
              <p-checkbox-group
                @change="onColSettingsChange"
                v-model="settingColumns"
                :defaultValue="settingColumns"
              >
                <p-row>
                  <template v-for="item in defColumns">
                    <template v-if="item.key != 'rowIndex' && item.dataIndex != 'action'">
                      <p-col :span="12" ><p-checkbox :value="item.dataIndex">{{  item.title }}</p-checkbox></p-col >
                    </template>
                  </template>
                </p-row>
              </p-checkbox-group>
            </template>
            <a><p-icon type="setting" />自定义列</a>
          </p-popover>
        </span>
      </div>

      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :scroll="tableScroll"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          type:'radio',
        }"
        @change="handleTableChange"
        
      >
      <template slot="changeType" slot-scope="text,res">
           {{ changtype[text] }}
        </template>
        <template slot="billNum" slot-scope="text,res">
          <a @click="submitProcess(res)">{{text}}</a>
        </template>
        <template slot="billStatus" slot-scope="text">
          {{ list[text] }}
        </template>
        <template slot="packingMaterialRetention" slot-scope="text" >

          <p v-if="text==null?false:true">{{text.split(',').map(item=>{return InventoryPackaging[item]}).toString()}}</p>
        </template>
        
      </p-table>

      <!-- 新增选择单据类型 -->
      <p-modal
        title="请选择新增单据类型"
        :visible="winVisible"
        @ok="changeHandleOk"
        @cancel="handleCancel"
      >
        <p-form layout="inline">
          <p-row :gutter="24">
            <p-col :xl="24" :lg="7" :md="8" :sm="24">
              <p-form-item label="工艺更改类型">
                <p-select style="width: 240px" >
                  <p-select-option 
                    @click="ValueChange(item)"
                    :value="item.value"
                    v-for="item in processChange"
                    :key="item.value"
                    >{{ item.text }}</p-select-option
                  >
                </p-select>
              </p-form-item>
            </p-col>
          </p-row>
        </p-form>
      </p-modal>
      <!-- 呆滞品返工申请 -->
      <p-modal v-model="retentionVisible" @ok="retentionhandleOk" :footer="null" destroyOnClose="true" width="70%">
        <retentionApply ref="retentionVisible" :listData="listData" @closeretentionVisible="closeretentionVisible"></retentionApply>
      </p-modal>
      <!-- 在线返工申请 -->
      <p-modal v-model="OnlineReworkVisible" @ok="OnlineReworkOk" :footer="null" destroyOnClose="true" width="70%">
        <onlineRework :listData="listData"></onlineRework>
      </p-modal>

      <!-- 外协返工申请 -->
      <p-modal v-model="outReworkVisible" @ok="outReworkOk" :footer="null" destroyOnClose="true" width="70%">
        <outRework :listData="listData" @closeoutReworkVisible="closeoutReworkVisible"></outRework>
      </p-modal>

      <!-- 产品锁定明细 -->
      <p-modal
        v-model="lockdetailsVisible"
        title
        @ok="lockdetailsOk"
        width="70%"
      >
        <lockdetails></lockdetails>
      </p-modal>
      <!-- 产品更改明明细 -->
      <p-modal
        v-model="changedetailsVisible"
        title
        @ok="changedetailsOk"
        width="70%"
      >
        <changedetails></changedetails>
      </p-modal>
      <!-- 差异物料指派表 -->
      <p-modal v-model="differenceVisible" title @ok="differenceOk" width="70%">
        <difference></difference>
      </p-modal>
      <!-- 临时BOM物料分配表 -->
      <p-modal v-model="temporaryVisible" title @ok="temporaryOk" width="70%">
        <temporary></temporary>
      </p-modal>
    </div>
  </p-card>
</template>

<script>
import Vue from "vue";
import { filterObj } from "@/utils/util";
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import ButtonExpHandler from "@/components/jeecgbiz/modules/ButtonExpHandler";
import { postAction, getAction, deleteAction } from "@/api/manage";
import {
  initDictOptions,
  filterMultiDictText,
} from "@/components/dict/JDictSelectUtil";
import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
import retentionApply from "./modules/retentionApply";
import outRework from "./modules/outRework";

import lockdetails from "./modules/Lockdetails";
import changedetails from "./modules/Changedetails";
import difference from "./modules/difference";
import temporary from "./modules/temporary";
import onlineRework from "./modules/OnlineRework";
import { ajaxGetDictItems } from "@/api/api";
import moment from 'moment'

//高级查询modal需要参数
const superQueryFieldList = [
  {
    text: "单据号",
    type: "string",
    value: "type",
  },
  {
    text: "单据类型",
    type: "string",
    value: "fileUrl",
  },
  {
    text: "来源单号",
    type: "string",
    value: "updateBy",
  },
  {
    text: "单据日期",
    type: "string",
    value: "createBy",
  },
  {
    text: "制单人",
    type: "string",
    value: "createTime",
  },
  {
    text: "更改前产品编码",
    type: "string",
    value: "updateTime",
  },
  {
    text: "更改前产品名称",
    type: "string",
    value: "remark",
  },
  {
    text: "更改后产品编码",
    value: "action",
    type: "string",
  },
  {
    text: "更改后产品名称",
    value: "action",
    type: "string",
  },
  {
    text: "状态",
    value: "action",
    type: "string",
  },
  {
    text: "更改来源说明",
    value: "action",
    type: "string",
  },
  {
    text: "是否齐套",
    value: "action",
    type: "string",
  },
  {
    text: "产成品包材保留",
    value: "action",
    type: "string",
  },
  {
    text: "PCBA硬件升级",
    value: "action",
    type: "string",
  },
];
export default {
  name: "MesHrLqcPhotoList",
  mixins: [JeecgListMixin],
  provide() {
    return {
      userInfo: JSON.parse(this.userInfo),
    };
  },
  components: {
    JSuperQuery,
    retentionApply,
    lockdetails,
    changedetails,
    difference,
    temporary,
    outRework,
    onlineRework,
  },
  props: {
    mainId: {
      type: String,
      default: "",
      required: false,
    },
  },
    
  watch: {},
  data() {
    return {
      moment,
      userInfo: localStorage.getItem("employeeinfo"),
      size: "0",
      stateL:[],
      changeValue: {},
      winVisible: false,
      retentionVisible: false,
      lockdetailsVisible: false,
      outReworkVisible: false,
      changedetailsVisible: false,
      differenceVisible: false,
      temporaryVisible: false,
      OnlineReworkVisible: false,
      processChange: [],
      changtype:{},
      selectedRowKeys: [],
      selectUserRows: [],
      selectedData: [],
      fieldList: superQueryFieldList,
      queryParam: {
        billNum: "",
      },
      list: {},
      listData: {}, //在库呆滞品传给子组件参数
      EnhanceJS: "",
      cgButtonLinkList: [],
      InventoryPackaging:[],
      cgButtonList: [],
      code: "",
      // 表头
      columns: [],
      defColumns: [
        {
          title: "序号",
          dataIndex: "",
          key: "rowIndex",
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          title: "单据号",
          align: "center",
          dataIndex: "billNum",
          scopedSlots: { customRender: "billNum" },
        },
        {
          title: "工艺更改类型",
          align: "center",
          dataIndex: "changeType",
          scopedSlots: { customRender: "changeType" },
        },
        {
          title: "来源类型",
          align: "center",
          dataIndex: "",
        },
        {
          title: "来源单号",
          align: "center",
          dataIndex: "billOriNum",
        },
        {
          title: "单据日期",
          align: "center",
          dataIndex: "createTime",
        },
        {
          title: "制单人",
          align: "center",
          dataIndex: "createBy",
        },
        {
          title: "更改前产品编码",
          align: "center",
          dataIndex: "productCodeChangeBefore",
        },
        {
          title: "更改前产品名称",
          align: "center",
          dataIndex: "productCodeChangeBeforeName",
        },
        {
          title: "更改后产品编码",
          dataIndex: "productCodeChangeAfter",
          align: "center",
        },
        {
          title: "更改后产品名称",
          dataIndex: "productCodeChangeAfterName",
          align: "center",
        },
        {
          title: "状态",
          dataIndex: "billStatus",
          align: "center",
          scopedSlots: { customRender: "billStatus" },
        },
        {
          title: "更改来源说明",
          dataIndex: "productChangeExplain",
          align: "center",
        },
        {
          title: "是否齐套",
          dataIndex: "changeMaterialSet",
          align: "center",
          customRender:function(t){
            if(t=='false'){return '否'}
            if(t=='true'){return '是'}
            if(t==null){return null}
          }
        },
        {
          title: "产成品包材保留",
          dataIndex: "packingMaterialRetention",
          align: "center",
          scopedSlots: { customRender: "packingMaterialRetention" },
        },
        {
          title: "PCBA硬件升级",
          dataIndex: "pcbaUpgrade",
          align: "center",
          customRender:function(t){
            if(t=='false'){return '否'}
            if(t=='true'){return '是'}
            if(t==null){return null}
          }
        },
      ],
      url: {
        list: "/mes-craft/craft/mesPeBill/list",
      },
      dictOptions: {},
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "50"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
    };
  },
  computed:{
    bclist(text){
      let arr=text.split(',')
      let array=[]
      arr.forEach(item=>{
        array.push(this.InventoryPackaging.filter(items=>{return items.value==item})[0].value)
      })
      return array.toString()
    },
    tableScroll:function(){
         if(this.columns.length > 13){
             return { x: this.columns.length*150-450 }
         }
     }
  },
  created() {
    this.lodacontent();
  },
  mounted(){
    this.setdefColumns();
    this.initColumns();
    this.loadData();
  },
  methods: {
    onSearch() {
      this.loadData();
    },
    setdefColumns() {
      if (this.defColumns.length > 10) {
        let arrLength = this.defColumns.length - 1;
        // this.defColumns[arrLength]["fixed"] = "right";
        this.defColumns[arrLength]["width"] = 200;
        this.defColumns[0]["width"] = 70;
        this.defColumns[0]["fixed"] = "left";
      }
    },
    
    // 新增参数
    handleAdd() {
      this.$router.push({ path: this.$route.path,query: { handle: "edit",},});
      this.winVisible = true;
    },
    handleChange(){
      if(this.selectedData.length>0){
      this.$router.push({ path: this.$route.path,query: { handle: "edit",},});
      let list=this.selectedData[0]
      let type=this.selectedData[0].changeType
      this.listData=this.selectedData[0]
      this.listData.typeChange=this.processChange.filter((item) => { return item.value == type;})[0];
      this.listData.hand='change'
      this.listData.Approval=false
      
      // 判断弹窗内容是否可编辑
       if(data.billStatus==0){
        this.listData.isNewAdd = false;
        this.listData.Approval=true
      }else {
        this.listData.isNewAdd = true;
        this.listData.Approval=false
      }
      let index=list.changeType
      this.condition(index)
      }else{
        this.$message.error('请选择一条工单')
      }
     
    },
    // 判断哪种更改单
    condition(index){
      if (index == 1 || index == 3) {
        this.retentionVisible = true;
        this.listData.isTypeA = true;
      } else if (index == 2 || index == 4) {
        this.retentionVisible = true;
        this.listData.isTypeA = false;
      } else if (index == 5) {
        this.OnlineReworkVisible = true;
        this.$router.push({ path: this.$route.path,query: { handle: "edit",typeid:5},});
      } else if (index == 6) {
        this.outReworkVisible = true;
      }
    },
    submitProcess(data){
      let type=data.changeType
      this.listData=data
      this.listData.typeChange=this.processChange.filter((item) => { return item.value == type;})[0];
      this.$router.push({ path: this.$route.path,query: { handle: "edit",},});
      this.listData.hand='change'
      if(data.billStatus==0){
        this.listData.isNewAdd = false;
        this.listData.Approval=true
      }else {
        this.listData.isNewAdd = true;
        this.listData.Approval=false
      }
      let index=data.changeType
      this.condition(index)
    },
    
    changeHandleOk() {
      this.winVisible = false;
      this.listData = {};
      this.listData.Approval=true
      let index = this.changeValue.value;
      this.condition(index)
      this.listData.isNewAdd = false;
      this.listData.hand='add'
      this.listData.typeChange = this.changeValue;
    },
    handleCancel() {
      this.winVisible = false;
    },
    ValueChange(data) {
      this.changeValue = data;
    },
    handleSizeChange(e) {
      this.size = e.target.value;
      this.loadData();
    },
    lockdetailsOk() {
      this.lockdetailsVisible = false;
    },
    changedetailsOk() {
      this.changedetailsVisible = false;
    },
    differenceOk() {
      this.differenceVisible = false;
    },
    temporaryOk() {
      this.temporaryVisible = false;
    },
    closeretentionVisible(){
      this.retentionhandleOk()
      this.loadData()
    },
    closeoutReworkVisible(){
      console.log('我开始关闭外协弹窗')
      this.outReworkOk()
      this.loadData()
    },
    closeonlineRework(){
      this.OnlineReworkOk()
      this.loadData()
    },
    retentionhandleOk() {
      this.retentionVisible = false;
      this.loadData()
    },
    outReworkOk() {
      this.outReworkVisible = false;
    },
    OnlineReworkOk() {
      this.OnlineReworkVisible = false;
    },

    //高级查询方法
    handleSuperQuery(arg) {
      if (!arg) {
        this.superQueryParams = "";
        this.superQueryFlag = false;
      } else {
        this.superQueryFlag = true;
        this.superQueryParams = JSON.stringify(arg);
      }
      this.loadData();
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
      var key = this.$route.name + ":colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        });
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter((item) => {
          if (item.key == "rowIndex" || item.dataIndex == "action") {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        });
        this.columns = cols;
      }
    },
    onSelectChange (selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys[0]
        this.selectionRows = selectionRows
        this.selectedData = selectionRows
    },
    // 列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000);
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
      this.loadData()
    },
    // 数据加载
    loadData(arg) {
      if (!this.url || !this.url.list) {
        console.log("请设置url.list属性!");
        return;
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams(); // 查询条件
      this.loading = true;
      console.log(params);
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.data.records;
          this.ipagination.total = res.data.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.$nextTick(() => {
          this.loading = false;
        });
      });
    },
    getQueryParams() {
      // 获取查询条件
      const sqp = {};
      if (this.superQueryParams) {
        sqp["superQueryParams"] = encodeURI(this.superQueryParams);
      }
      var param = Object.assign(sqp, this.queryParam);
      param.billStatus = this.size;
      param.billNum = this.queryParam.billNum;
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      param.limit = this.ipagination.pageSize;
      return filterObj(param);
    },
    lodacontent() {
      ajaxGetDictItems("mes_out_state").then(res=>{
          if(res.code==0){
              console.log('页面应该改变')
              this.state=res.data
          }else{
              this.$message.error(res.msg)
          }
      })
      ajaxGetDictItems("processChange").then((res) => {
        if (res.code == 0) {
          this.processChange = res.data;
          let obj={}
          res.data.forEach(res=>{
            obj[res.value]=res.text
          })
          this.changtype=obj
        } else {
          this.$message.error(res.msg);
        }
      });
      ajaxGetDictItems("mes_out_state").then((res) => {
        let obj = {};
        if (res.code == 0) {
          res.data.forEach((ele) => {
            obj[ele.value] = ele.text;
          });
          this.list = obj;
        } else {
          this.$message.error(res.msg);
        }
      });
      ajaxGetDictItems("InventoryPackaging").then(res=>{
         let obj = {};
             if(res.code==0){
                  res.data.forEach((ele) => {
                    obj[ele.value] = ele.text;
                  });
                  this.InventoryPackaging=obj
             }else{
                 this.$message.error(res.msg)
             }
      })
      
    },
  },
};
</script>
<style scoped>
@import "~@assets/less/common.less";
</style>
